package com.insight.modules.system.controller;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqiao.insight.acore.system.entity.ConfigureDictItem;
import com.yuanqiao.insight.acore.system.utils.ConfigureDictUtils;
import com.yuanqiao.insight.common.constant.CommonConstant;
import com.yuanqiao.insight.common.util.common.LocalCacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.mq.RedisMq;
import com.insight.common.mq.stream.Streams;
import com.insight.common.system.query.QueryGenerator;
import com.yuanqiao.insight.acore.system.entity.SysDictItem;
import com.yuanqiao.insight.acore.system.service.IConfigureDictItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @Author zhangweijian
 * @since 2018-12-28
 */
@RestController
@RequestMapping("/configure/dictItem")
@Slf4j
public class ConfigureDictItemController {

    @Autowired
    private IConfigureDictItemService configureDictItemService;
    @Autowired
    private ConfigureDictUtils configureDictUtils;
    @Autowired
    private RedisMq redisMq;

    /**
     * @param configureDictItem
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     * @功能：查询字典数据
     */
    @AutoLog(value = "配置字典-查询字典配置")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<ConfigureDictItem>> queryPageList(ConfigureDictItem configureDictItem, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {

        String itemText = configureDictItem.getItemText();
        configureDictItem.setItemText("");
        QueryWrapper<ConfigureDictItem> queryWrapper = QueryGenerator.initQueryWrapper(configureDictItem, req.getParameterMap());
        if (StringUtils.isNotEmpty(itemText)) {
            queryWrapper.like("item_text", itemText);
        }
        queryWrapper.orderByAsc("sort_order");
        queryWrapper.orderByDesc("create_time");
        Page<ConfigureDictItem> page = new Page<ConfigureDictItem>(pageNo, pageSize);
        IPage<ConfigureDictItem> pageList = configureDictItemService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * @return
     * @功能：新增
     */
    @AutoLog(value = "配置字典-新增字典配置")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<?> add(@RequestBody ConfigureDictItem configureDictItem) {
        configureDictItem.setCreateTime(new Date());
        List<ConfigureDictItem> itemList = configureDictItemService.list(new QueryWrapper<ConfigureDictItem>().eq("item_text", configureDictItem.getItemText()).eq("dict_id", configureDictItem.getDictId()));
        if (CollUtil.isNotEmpty(itemList)) {
            return Result.error("字典配置项名称重复！");
        }
        configureDictItemService.save(configureDictItem);
        sendEvent();
        return Result.OK("添加成功！");
    }

    /**
     * @param configureDictItem
     * @return
     * @功能：编辑
     */
    @AutoLog(value = "配置字典-编辑字典配置项")
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public Result<?> edit(@RequestBody ConfigureDictItem configureDictItem) {
        configureDictItem.setUpdateTime(new Date());
        List<ConfigureDictItem> itemList = configureDictItemService.list(new QueryWrapper<ConfigureDictItem>().ne("id", configureDictItem.getId()).eq("item_text", configureDictItem.getItemText()).eq("dict_id", configureDictItem.getDictId()));
        if (CollUtil.isNotEmpty(itemList)) {
            return Result.error("字典配置项名称重复！");
        }
        configureDictItemService.updateById(configureDictItem);
        sendEvent();
        return Result.OK("字典配置项编辑成功！");
    }

    /**
     * @param id
     * @return
     * @功能：删除字典数据
     */
    @AutoLog(value = "配置字典-删除字典配置项")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        configureDictItemService.removeById(id);
        sendEvent();
        return Result.OK("字典配置项删除成功！");
    }

    /**
     * 发布配置字典全量刷新事件
     */
    private void sendEvent() {
        redisMq.publish(Streams.CONFIGURE_DICT_REFRESH, new JSONObject());
    }

    /**
     * @param parentCode
     * @param childCode
     * @return
     * @功能：获取字典项数据
     */
    @RequestMapping(value = "/getItemValue", method = RequestMethod.GET)
    public Result<SysDictItem> getItemValue(@RequestParam(name = "parentCode", required = true) String parentCode, String childCode) {
        Result<SysDictItem> result = new Result<SysDictItem>();
        String dictItem = configureDictUtils.getValueByKeyFromDataDict(parentCode, childCode) + "";
        result.setSuccess(true);
        result.setResult(dictItem);
        return result;
    }

    /**
     * @param parentCode
     * @return
     * @功能：获取字典子项数据键值对集合
     */
    @RequestMapping(value = "/getItemMap", method = RequestMethod.GET)
    public Result<?> getItemMap(@RequestParam(name = "parentCode", required = true) String parentCode, String noPrefix) {
        Result<Map<String, Object>> result = new Result<>();
        LocalCacheUtils cacheUtils = LocalCacheUtils.getInstance();
        Map<String, Object> map = cacheUtils.filterGetValueByKey(parentCode);
        JSONArray array = new JSONArray();
        if (CollUtil.isNotEmpty(map)) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                JSONObject eleObj = new JSONObject();
                String key = entry.getKey();
                if (StringUtils.isNotEmpty(noPrefix) && noPrefix.equals("true")) {
                    key = key.replace(CommonConstant.DATA_DICT_KEY + parentCode + "_", "");
                }
                eleObj.put("name", key);
                eleObj.put("value", entry.getValue());
                array.add(eleObj);
            }
            result.setSuccess(true);
            result.setResult(array);
        } else {
            result.setSuccess(false);
            result.setResult(array);
        }
        return result;
    }


}
